package com.flycent.hqhs.ui;

import java.lang.ref.WeakReference;
import java.util.List;
import java.util.TimerTask;

import net.tsz.afinal.FinalActivity;
import net.tsz.afinal.annotation.view.ViewInject;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.flycent.hqhs.App;
import com.flycent.hqhs.R;
import com.flycent.hqhs.bean.MyArea;
import com.flycent.hqhs.http.WebClient;
import com.flycent.hqhs.http.WebException;
import com.flycent.hqhs.ui.view.SimpleTitleBar;
import com.flycent.hqhs.util.StringUtil;

/**
 *  新建地址
 * @author fbl
 */
public class NewAddressActivity extends BackableTitleBarActivity{
	@ViewInject(id = R.id.mname_edit) EditText mTrueName;
	@ViewInject(id = R.id.telephone_edit) EditText mTelNumber;
	@ViewInject(id = R.id.fixed_telephone_edit) EditText mFixTelNumber;
	@ViewInject(id = R.id.address_text , click = "butClick") TextView mAddress;
	@ViewInject(id = R.id.detail_address_edit) EditText mDetailAddress;
	@ViewInject(id = R.id.address_zipCode_edit) EditText mZipCode;
	@ViewInject(id = R.id.address_is_default_img , click = "butClick") ImageView mDefaultImg;

	private List<MyArea> areas;
	private String mAreaId;
	private String mAddressStr;
	private String inputType; 
	private String mId,consignee,areaName,phone,fixphone,address,marea,zipCode;
	private boolean isAdd = false;
	private boolean isDefault = false;
	private  String from = "";
	private Dialog dialog;
	private Handler mHandler = new MyHandler(this);


	@Override
	protected void onCreate(Bundle savedInstance) {
		super.onCreate(savedInstance);
		inputType = getIntent().getStringExtra("inputType");
		from = getIntent().getStringExtra("from");
		setContentView(R.layout.activity_new_address);
		FinalActivity.initInjectedView(this);

		if("add".equals(inputType)){
			isAdd = true;
		}else if("modify".equals(inputType) ){
			isAdd = false;
			mId = getIntent().getStringExtra("id");
			consignee = getIntent().getStringExtra("consignee");
			areaName = getIntent().getStringExtra("areaName");
			phone = getIntent().getStringExtra("phone");
			address = getIntent().getStringExtra("address");
			marea = getIntent().getStringExtra("marea");
			zipCode = getIntent().getStringExtra("zipCode");
			isDefault = getIntent().getBooleanExtra("isDefault", false);

			mTrueName.setText(consignee);
			mTelNumber.setText(phone);
			mAddress.setText(areaName);
			mDetailAddress.setText(address);
			mZipCode.setText(zipCode);

			mAreaId = marea;

			if( isDefault ){
				mDefaultImg.setImageResource(R.drawable.address_check_show);	
			}else {
				mDefaultImg.setImageResource(R.drawable.address_check_disable);
			}

		}

	}


	@Override
	protected void onTitleBarCreated(SimpleTitleBar titleBar) {
		super.onTitleBarCreated(titleBar);
		if("add".equals(inputType)){
			titleBar.setTitle(R.string.title_new_address);
		}else if("modify".equals(inputType) ){
			titleBar.setTitle(R.string.title_modify_address);
		}

		titleBar.setRightButtonText(R.string.title_right_save);
		titleBar.setOnRightButtonClickListener(new OnClickListener() {

			@Override
			public void onClick(View paramView) {

				if(invalidateText(mTrueName, R.string.please_input_truename)
						|| invalidateText(mTelNumber, R.string.please_input_telphonenum)
						|| invalidateText(mAddress, R.string.please_select_address)
						|| invalidateText(mDetailAddress, R.string.please_input_detailaddress)
						|| invalidateText(mZipCode,R.string.please_input_zipcode)
						){
					return;
				}
				if(!StringUtil.validatePhoneNo(mTelNumber)){
					App.showShortToast(getString(R.string.please_input_telphonenum));	
					return;
				}
				if(!StringUtil.isZipCode(getText(mZipCode))){
					App.showShortToast(getString(R.string.please_input_true_zipcode));
					return;
				}

				if( isAdd ){
					doSaveAddress();
				}else {
					doModifyAddress();
				}

			}

		});
	}

	/** 新建地址*/
	private void doSaveAddress() {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					WebClient.getInstance(NewAddressActivity.this).checkNewAddress(
							getText(mDetailAddress),
							getText(mTrueName),
							isDefault,
							getText(mTelNumber), 
							getText(mZipCode), 
							mAreaId);
					mHandler.sendEmptyMessage(2);
				} catch (WebException e) {
					dismissLoadingDialog();
					e.printStackTrace();
				}

			};
		}.start();

	}
	/** 修改地址 */
	private void doModifyAddress() {
		showLoadingDialog("");
		new Thread(){
			public void run() {
				try {
					WebClient.getInstance(NewAddressActivity.this).modifyAddress(
							mId,
							getText(mDetailAddress),
							getText(mTrueName),
							isDefault,
							getText(mTelNumber), 
							getText(mZipCode), 
							mAreaId);
					mHandler.sendEmptyMessage(2);
				} catch (WebException e) {
					dismissLoadingDialog();
					e.printStackTrace();
				}

			};
		}.start();

	}

	public void butClick(View v){
		if(v == mAddress ){
			// 虚拟键盘隐藏 判断view是否为空
			View view = NewAddressActivity.this.getWindow().peekDecorView();
			if (view != null) {
				//隐藏虚拟键盘
				InputMethodManager inputmanger = (InputMethodManager) NewAddressActivity.this
						.getSystemService(MainActivity.INPUT_METHOD_SERVICE);
				inputmanger.hideSoftInputFromWindow(view.getWindowToken(),
						0);
			}

			showAreaSelectDialog("",true);


		}
		if( v == mDefaultImg ){

			if( isDefault){
				mDefaultImg.setImageResource(R.drawable.address_check_disable);
				isDefault = false;
			}else {
				mDefaultImg.setImageResource(R.drawable.address_check_show);
				isDefault = true;
			}

		}


	}


	/**
	 * @param sid  Area 地区id
	 * @param isFirst   是否是第一次显示
	 */
	private void showAreaSelectDialog(final String sid ,Boolean isFirst) {
		if(dialog != null && dialog.isShowing() ){
			dialog.dismiss();
		}

		if( isFirst ){
			mAddressStr = "";
		}
		showLoadingDialog("",false);

		new Thread(){
			public void run() {
				try {
					areas =  WebClient.getInstance(NewAddressActivity.this).area(sid);
					if( areas.size() == 0){
						mAreaId = sid;
						App.showLog("mAreaId=="+mAreaId);
						mHandler.sendEmptyMessage(1);
						return;
					}
					App.showLog("areas=="+areas);
				} catch (WebException e) {
					dismissLoadingDialog();
					e.printStackTrace();
				}
				mHandler.sendEmptyMessage(0);
			};
		}.start();



	}
	
	@SuppressLint("HandlerLeak") 
	private class MyHandler extends Handler{
		
		private WeakReference<Activity> mActivity;
		
		private MyHandler(Activity activity){
			mActivity = new WeakReference<Activity>(activity);
		}
		
		@Override
		public void dispatchMessage(Message msg) {
			super.dispatchMessage(msg);
			if( mActivity.get() != null ){
				switch (msg.what) {
				case 0:
					dismissLoadingDialog();
					ShowCitySelectDialog();
					break;

				case 1:
					dismissLoadingDialog();
					mAddress.setText(mAddressStr);
					break;
				case 2:
					dismissLoadingDialog();
					if("SubmitOrderActivity".equals(from)){
						setResult(100); //为了让提交订单中地址可以刷新
					}
					finish();
					break;

				default:
					break;
				}
				
				
			}
		}
	}
	


	private void ShowCitySelectDialog(){

		String [] ss = new String[areas.size()];
		for (int i = 0; i < ss.length; i++) {
			ss[i] = areas.get(i).getName();
		}

		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle("选择地址");
		builder.setIcon(android.R.drawable.ic_dialog_info);
		builder.setCancelable(false);
		builder.setSingleChoiceItems(ss, 0,
				new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface dialog1, int which) {
				String aid = areas.get(which).getId();
				mAddressStr = mAddressStr+areas.get(which).getName();
				dialog.dismiss();
				showAreaSelectDialog(aid, false);
			}
		});
		builder.setNegativeButton("取消", null);

		dialog = builder.show();

	}
	private void canclick(boolean b){
		mAddress.setClickable(b);
	}

	TimerTask task = new TimerTask() {
		@Override
		public void run() {
			canclick(true);
		}
	};
	
	protected void onDestroy() {
		super.onDestroy();
		mHandler.removeCallbacksAndMessages(null);
	};

}
